﻿namespace PersonaLibrary.Data
{
	using System;
	using System.Linq;
	using System.Data.Linq;

	public partial class LinqToDbDataContext : ILinqToDbContext
	{
		public static event Action<BaseEntity> ItemAdded;
		public static event Action<BaseEntity> ItemUpdated;
		public static event Action<BaseEntity> ItemDeleted;
		
		public void SubmitChangesWithOutPartial()
		{
			base.SubmitChanges(ConflictMode.FailOnFirstConflict);
		}

		public override void SubmitChanges(ConflictMode failureMode)
		{
			var items = GetChangeSet();
			foreach (BaseEntity item in items.Inserts.Cast<BaseEntity>())
			{
				if(!(item is Employee) || !item.UpdateDate.HasValue)
					item.UpdateDate = DateTime.Now;
				var result = GetUserName().FirstOrDefault(x => x != null);
				item.UserName = result.Column1;
			}
			foreach (BaseEntity item in items.Updates.Cast<BaseEntity>())
			{
				if (!(item is Employee) || !item.UpdateDate.HasValue)
					item.UpdateDate = DateTime.Now;
				var result = GetUserName().FirstOrDefault(x => x != null);
				item.UserName = result.Column1;
			}

			base.SubmitChanges(failureMode);
			
			foreach (var item in items.Inserts)
				if (ItemAdded != null) ItemAdded((BaseEntity) item);
			foreach (var item in items.Updates)
				if (ItemUpdated != null) ItemUpdated((BaseEntity)item);
			foreach (var item in items.Deletes)
				if (ItemDeleted != null) ItemDeleted((BaseEntity)item);
		}

		public void SubmitChanges(bool useEvents)
		{
			if(useEvents)
				SubmitChanges(ConflictMode.FailOnFirstConflict);
			else
				base.SubmitChanges(ConflictMode.FailOnFirstConflict);
		}
	}
}
